// socketManager.js
const socketIO = require('socket.io');
const db = require('../model/socketDB');

function initializeSocket(server) {
  const io = socketIO(server);

  io.on('connection', async (socket) => {
    //获取到在线用户信息
    
    // console.log(now_num)
    console.log('A user connected');

    socket.on('login',async data=>{
        const now_user = await db.GETONLINE();
        const isOnline = now_user.find(item=>item.username === data.username)
        if(isOnline){
            //如果用户存在，这属于重复登录，
            socket.emit('logerror',{state:'400',msg:'登录失败'})    
        }else{
            //用户不存在
            socket.emit('logsuccess',{state:'299',msg:'登录成功'})
            const rows = await db.INSERTONLINE(data.username,data.logo);
            console.log('登录成功',rows);

            io.emit('addUser',{username:data.username})
            
            //获取到当前在线人数
            const online = await db.GETONLINE();
            const online_num = online.length;
            io.emit('onlineNum',{num:online_num})//数据库获取

            //把登录成功用户的用户名存储起来
            socket.username = data.username
            console.log(socket.username);
            socket.password = data.password
        }
    })

    // 监听客户端发送的消息
    socket.on('chat message', (data) => {
      console.log(`Message from client: ${data.msg}`);

      // 广播消息给所有连接的客户端
      io.emit('chat message', data);
    });

    //监听客户端发送建立对战房间申请
    socket.on('compaign',async data=>{
      try{
        const add_room = await db.ADDROOM(data.username);
        const add_topic = await db.ADDTOPIC(data.username);
        //获得题目
        // const topic = await db.GETTOPIC(data.username)
        // console.log(topic[0].topic);
        socket.emit('add_room',{
          state:299,
          msg:"房间已建立成功"
        })
      }catch(error){
        socket.emit('add_room',{
          state:400,
          msg:error.message
        })
      }
    })

    //监听用户发送进入房间申请
    socket.on('enter_room',async data=>{
      const enter_room = await db.ENTERROOM(data.username);
      console.log(enter_room[0]);
      //匹配好后发给房主匹配者信息
      io.emit('vs_start',{        
        vs_people:enter_room[0].guest,
        send_to:enter_room[0].host,
        topic: JSON.parse(enter_room[0].topic)[0]
      })
      //匹配好后发给匹配者房主信息
      io.emit('vs_people',{
        vs_people:enter_room[0].host,
        send_to:enter_room[0].guest,
        topic: JSON.parse(enter_room[0].topic)[0]
      })
    })

    //监听用户答题情况
    socket.on('select',async data=>{
      if(data.select.includes('h')){
        //若字符串中含有h字符，则证明是房主发来的消息
        const addh = await db.ADDHA(data.username,data.add_score);        
      }else{
        //字符中不含h字符，则证明是匹配者发来的消息
        const addg = await db.ADDGA(data.username,data.add_score);
      }
      const isComplete = await db.JUDGENEXT(data.username);
      if(isComplete.isComplete){
        //console.log("发送答案请求");
        //获取room信息
        const room_msg = await db.GETROOM(data.username);
        io.emit('answer',{
          send_toh:room_msg.host,
          send_tog:room_msg.guest,
          score_h:room_msg.answer_host,
          score_g:room_msg.answer_guest,
        })
        io.emit('next_topic',{
          send_toh:room_msg.host,
          send_tog:room_msg.guest,
          topic: JSON.parse(room_msg.topic)[room_msg.topic_no]
        })
      }else{
        console.log("等一会",isComplete.isComplete)
      }
    })

    // 监听客户端断开连接
    socket.on('disconnect', async() => {
        const del_now_user = await db.DELETEONLINE(socket.username);
        io.emit('exitUser',{
            username:socket.username
        })
        const online = await db.GETONLINE();
        const online_num = online.length;
        io.emit('onlineNum',{num:online_num})//数据库获取

        console.log('User disconnected');
    });
  });
}

module.exports = initializeSocket;

